package com.rds.workflow.controller;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rds.common.annotation.SysElasticSearchMapper2;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.SysDept;
import com.rds.common.core.domain.entity.SysRole;
import com.rds.common.core.domain.entity.SysUser;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.redis.RedisCache;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.EsUtils;
import com.rds.common.utils.MapUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.system.domain.RdaPolicy;
import com.rds.system.domain.Sharing;
import com.rds.system.service.*;
import com.rds.workflow.domain.*;
import com.rds.workflow.service.*;
import com.rds.workflow.utils.WorkflowStateid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/pms/workflowMGMT")
public class RdaWorkflowTempleteController extends BaseController {

    @Autowired
    private IRdaWorkflowTempleteService rdaWorkflowTempleteService;

    @Autowired
    private IRdaNodeTempleteService rdaNodeTempleteService;

//    @Autowired
//    private SysElasticSearchMapper2 sysElasticSearchMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IRdaWorkflow2NodeTempleteRelService rdaWorkflow2NodeTempleteRelService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RdaWorkflowTempleteScopeService rdaWorkflowTempleteScopeService;

    /*添加自动命令***/
    @Autowired
    private IRdaNameCodeService nameCodeService;

    /*添加历史记录**/
    @Autowired
    private ISysHistoryService sysHistoryService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询流程模板列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:template')")
    @GetMapping("/template")
    public TableDataInfo template(RdaWorkflowTemplete rdaWorkflowTemplete){
        startPage();
        return getDataTable(rdaWorkflowTempleteService.selectRdaWorkflowTempleteList(rdaWorkflowTemplete));
    }

    /**
     * 获取流程模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:query')")
    @GetMapping(value = "/template/{id}")
    public AjaxResult getTemplateInfo(@PathVariable("id") Long id){
        return AjaxResult.success(rdaWorkflowTempleteService.selectRdaWorkflowTempleteById(id));
    }

    /**
     * 获取流程模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyTemplate')")
    @GetMapping(value = "/modifyTemplate/{id}")
    public AjaxResult modifyTemplate(@PathVariable("id") Long id){
        RdaWorkflowTemplete rdaWorkflowTemplete = rdaWorkflowTempleteService.selectRdaWorkflowTempleteById(id);
//        new HistoryRecordUtil(sysHistoryService).recordHistory(rdaWorkflowTemplete.getId(),"修改",rdaWorkflowTemplete.getStateid(),"流程模板","");
        //return AjaxResult.success(rdaWorkflowTempleteService.selectRdaWorkflowTempleteById(id));
        return AjaxResult.success(rdaWorkflowTemplete);
    }

    /**
     * 新增流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:addtemplate')")
    @PostMapping("/addtemplate")
    @Transactional
    public AjaxResult addtemplate(@RequestBody RdaWorkflowTemplete rdaWorkflowTemplete){
        Long id= SnowFlakeUtils.nextId();
        rdaWorkflowTemplete.setId(id);
        Long userId = SecurityUtils.getUserId();
        /*开始调用编码器 2021-12-22 begin**/
        Long typeId = Long.parseLong(String.valueOf(WorkflowStateid.workflowTempleteTypeid));
        String pageCode = rdaWorkflowTemplete.getCode();
        rdaWorkflowTemplete.setCode(nameCodeService.getNewCodeNameNo(typeId,pageCode));
        /*开始调用编码器 2021-12-22 end**/
        rdaWorkflowTemplete.setOwnerid(userId.intValue());
        rdaWorkflowTemplete.setTypeid(WorkflowStateid.workflowTempleteTypeid.intValue());
        rdaWorkflowTemplete.setPolicyid(WorkflowStateid.workflowTempletePolicyid.intValue());
        rdaWorkflowTemplete.setStateid(WorkflowStateid.workflowTempleteCreateid.intValue());
        int rows =rdaWorkflowTempleteService.insertRdaWorkflowTemplete(rdaWorkflowTemplete);
        insertStartEnd(rdaWorkflowTemplete);
       /* StringBuffer details=new StringBuffer();
        String typeName= MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getTypeid()));//类型
        String PolicyName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getPolicyid()));//策略
        String StateName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getStateid()));//状态
        details.append("类型="+typeName+",策略="+PolicyName+",状态="+StateName+",编码="+rdaWorkflowTemplete.getCode()+"");
        details.append(",名称="+rdaWorkflowTemplete.getName()+",描述="+rdaWorkflowTemplete.getDescription()+"");
        EsUtils.addHistory(sysElasticSearchMapper,id,"新增",details.toString(),"流程模板");*/
        System.out.println("id = " + id);
        System.out.println("stateid = " + rdaWorkflowTemplete.getStateid());
//        new HistoryRecordUtil(sysHistoryService).recordHistory(id,"创建",rdaWorkflowTemplete.getStateid(),"流程模板","");
        return toAjax(rows);
    }

    /**
     * 删除流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:removeTemplate')")
    @DeleteMapping("/removeTemplate/{ids}")
    @Transactional
    public AjaxResult removetemplate(@PathVariable Long[] ids){
        return toAjax(rdaWorkflowTempleteService.deleteRdaWorkflowTempleteByIds(ids));
    }

    /**
     * 修改流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:template')")
    @PutMapping("/template")
    @Transactional
    public AjaxResult updateTemplate(@RequestBody RdaWorkflowTemplete rdaWorkflowTemplete){
        rdaWorkflowTemplete.setModifyTime(DateUtils.getNowDate());
        return toAjax(rdaWorkflowTempleteService.updateRdaWorkflowTemplete(rdaWorkflowTemplete));
    }

    /**
     * 修改流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyTemplate')")
    @PutMapping("/modifyTemplate")
    @Transactional
    public AjaxResult modifyTemplate(@RequestBody RdaWorkflowTemplete rdaWorkflowTemplete){
        RdaWorkflowTemplete workflowTemplete=rdaWorkflowTempleteService.selectRdaWorkflowTempleteById(rdaWorkflowTemplete.getId());
        /*StringBuffer details=new StringBuffer();
        String typeName=MapUtils.getTranscoding(redisCache,Long.valueOf(workflowTemplete.getTypeid()));//类型
        String PolicyName=MapUtils.getTranscoding(redisCache,Long.valueOf(workflowTemplete.getPolicyid()));//策略
        String StateName=MapUtils.getTranscoding(redisCache,Long.valueOf(workflowTemplete.getStateid()));//状态
        String newTypeName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getTypeid()));//类型
        String newPolicyName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getPolicyid()));//策略
        String newStateName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTemplete.getStateid()));//状态
        details.append("旧值：类型="+typeName+",策略="+PolicyName+",状态="+StateName+",编码="+workflowTemplete.getCode()+"");
        details.append(",名称="+workflowTemplete.getName()+",描述="+workflowTemplete.getDescription()+"");
        details.append("\n新值：类型="+newTypeName+",策略="+newPolicyName+",状态="+newStateName+",编码="+rdaWorkflowTemplete.getCode()+"");
        details.append(",名称="+rdaWorkflowTemplete.getName()+",描述="+rdaWorkflowTemplete.getDescription()+"");
        EsUtils.addHistory(sysElasticSearchMapper,rdaWorkflowTemplete.getId(),"修改",details.toString(),"流程模板");*/
        rdaWorkflowTemplete.setModifyTime(DateUtils.getNowDate());
        return toAjax(rdaWorkflowTempleteService.updateRdaWorkflowTemplete(rdaWorkflowTemplete));
    }

    /**
     * 查询流程模板节点列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeList')")
    @GetMapping("/nodeList")
    public TableDataInfo nodeList(RdaNodeTemplete rdaNodeTemplete){
        startPage();
        return getDataTable(rdaNodeTempleteService.selectRdaNodeTemplete(rdaNodeTemplete.getWorkflowid()));
    }


    /**
     * 查询用户
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:user')")
    @GetMapping("/user")
    public TableDataInfo user(SysUser user){
        List<SysUser> list = userService.selectUserList(user);
        List<RdaNodeTemplete> idName=new ArrayList<RdaNodeTemplete>();
        list.forEach((SysUser sysUser) -> {
            RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
            rdaNodeTemplete.setId(sysUser.getUserId());
            rdaNodeTemplete.setDescription(sysUser.getUserName());
            idName.add(rdaNodeTemplete);
        });

        return getDataTable(idName);
    }


    /**
     * 查询角色
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:role')")
    @GetMapping("/role")
    public TableDataInfo role(){
        List<RdaNodeTemplete> idName=new ArrayList<RdaNodeTemplete>();
        List<SysRole> roles = roleService.selectRoleAll();
        roles.forEach((SysRole sysRole) -> {
            RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
            rdaNodeTemplete.setId(sysRole.getRoleId());
            rdaNodeTemplete.setDescription(sysRole.getRoleName());
            idName.add(rdaNodeTemplete);
        });
        return getDataTable(idName);
    }

    /**
     * 查询流程模板节点图列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeFlowChartList')")
    @GetMapping("/nodeFlowChartList")
    public AjaxResult nodeFlowChartList(RdaNodeTemplete rdaNodeTemplete){
//        startPage();
        Map<String,Object> info = new HashMap<>();
        List<RdaNodeTemplete>  ApproveList=rdaNodeTempleteService.selectRdaNodeTemplete(rdaNodeTemplete.getWorkflowid());
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel=new RdaWorkflow2NodeTempleteRel();
        rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
        List<RdaWorkflow2NodeTempleteRel> RejectList=rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelList(rdaWorkflow2NodeTempleteRel);
        rdaWorkflow2NodeTempleteRel=new RdaWorkflow2NodeTempleteRel();
        rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
        List<RdaWorkflow2NodeTempleteRel> workflow2NodeTempleteRelList=rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelAllList(rdaWorkflow2NodeTempleteRel);
        info.put("nodeList",ApproveList);
        info.put("Reject",RejectList);
        info.put("workflowPath",workflow2NodeTempleteRelList);
        return AjaxResult.success(info);
    }

    /**
     * 查询流程模板节点列表详情
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeList')")
    @GetMapping("/nodeList/{id}")
    public AjaxResult nodeList(@PathVariable("id") Long id){
        return AjaxResult.success(rdaNodeTempleteService.selectRdaNodeTempleteById(id));
    }



    /**
     * 新增流程节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:addNode')")
    @PostMapping("/addNode")
    @Transactional
    public AjaxResult addNode(@RequestBody RdaNodeTemplete rdaNodeTemplete){
        if("是".equals(rdaNodeTemplete.getIsWithdraw()) && "2".equals(rdaNodeTemplete.getIsRejectTostart())){
            return error("该节点不允许回收");
        }
        if(rdaNodeTemplete.getAppovedScript()!=null && rdaNodeTemplete.getAppovedScript()!=""){
            if(checkScenario(rdaNodeTemplete.getAppovedScript())==false){
                return error("执行脚本格式错误");
            }
        }
        if(rdaNodeTemplete.getRejecttostartScript()!=null && rdaNodeTemplete.getRejecttostartScript()!=""){
            if(checkScenario(rdaNodeTemplete.getRejecttostartScript())==false){
                return error("拒绝到开始处理程序格式错误");
            }
        }
        int rows =rdaNodeTempleteService.insertRdaNodeTemplete(rdaNodeTemplete);
        return toAjax(rows);
    }

    /**
     * 删除流程节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:deleteNode')")
    @DeleteMapping("/deleteNode/{ids}")
    @Transactional
    public AjaxResult deleteNode(@PathVariable Long[] ids){
        return toAjax(rdaNodeTempleteService.deleteRdaNodeTempleteByIds(ids));
    }
    /**
     * 修改流程节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeList')")
    @PutMapping("/nodeList")
    @Transactional
    public AjaxResult updateNode(@RequestBody RdaNodeTemplete rdaNodeTemplete){
        if("是".equals(rdaNodeTemplete.getIsWithdraw())&& "2".equals(rdaNodeTemplete.getIsRejectTostart())){
            return error("该节点不允许回收");
        }
        if(rdaNodeTemplete.getAppovedScript()!=null && rdaNodeTemplete.getAppovedScript()!=""){
            if(checkScenario(rdaNodeTemplete.getAppovedScript())==false){
                return error("执行脚本格式错误");
            }
        }
        if(rdaNodeTemplete.getRejecttostartScript()!=null && rdaNodeTemplete.getRejecttostartScript()!=""){
            if(checkScenario(rdaNodeTemplete.getRejecttostartScript())==false){
                return error("拒绝到开始处理程序格式错误");
            }
        }
        rdaNodeTemplete.setModifyTime(DateUtils.getNowDate());
        return toAjax(rdaNodeTempleteService.updateRdaNodeTemplete(rdaNodeTemplete));
    }

    /**
     * 查询流程模板节点拒绝列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeRefuseList')")
    @GetMapping("/nodeRefuseList")
    public TableDataInfo nodeRefuseList(RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel){
        startPage();
        return getDataTable(rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelList(rdaWorkflow2NodeTempleteRel));
    }

    /**
     * 拒绝列表新增流程节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:addRefuseNode')")
    @PostMapping("/addRefuseNode")
    @Transactional
    public AjaxResult refuseNodeAdd(@RequestBody RdaNodeTemplete rdaNodeTemplete){
        if(rdaNodeTemplete.getRejectScript()!=null && rdaNodeTemplete.getRejectScript()!=""){
            if(checkScenario(rdaNodeTemplete.getRejectScript())==false){
                return error("执行脚本格式错误");
            }
        }
        int rows =rdaNodeTempleteService.insertRdaNodeTempleteRefuse(rdaNodeTemplete);
        return toAjax(rows);
    }

    /**
     * 删除拒绝节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:removerRefuseNode')")
    @DeleteMapping("/removerRefuseNode/{ids}")
    @Transactional
    public AjaxResult removerRefuseNode(@PathVariable Long[] ids){
        return toAjax(rdaWorkflow2NodeTempleteRelService.deleteRdaWorkflow2NodeTempleteRel(ids));
    }

    /**
     * 查询拒绝节点详情
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyRefuseNode')")
    @GetMapping("/modifyRefuseNode/{id}")
    public AjaxResult modifyRefuseNode(@PathVariable("id") Long id){
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel=rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelByid(id);
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        rdaNodeTemplete.setId(rdaWorkflow2NodeTempleteRel.getId());
        rdaNodeTemplete.setSuperiorNodeId(rdaWorkflow2NodeTempleteRel.getFromid());
        rdaNodeTemplete.setLowerNodeId(rdaWorkflow2NodeTempleteRel.getToid());
        rdaNodeTemplete.setRejectScript(rdaWorkflow2NodeTempleteRel.getRejectScript());
        return AjaxResult.success(rdaNodeTemplete);
    }

    /**
     * 修改拒绝节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyRefuseNode')")
    @PutMapping("/modifyRefuseNode")
    @Transactional
    public AjaxResult modifyRefuseNode(@RequestBody RdaNodeTemplete rdaNodeTemplete){
        if(rdaNodeTemplete.getRejectScript()!=null && rdaNodeTemplete.getRejectScript()!=""){
            if(checkScenario(rdaNodeTemplete.getRejectScript())==false){
                return error("执行脚本格式错误");
            }
        }
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel=new RdaWorkflow2NodeTempleteRel();
        rdaWorkflow2NodeTempleteRel.setId(rdaNodeTemplete.getId());
        rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getSuperiorNodeId());
        rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getLowerNodeId());
        rdaWorkflow2NodeTempleteRel.setOperationState(0L);
        rdaWorkflow2NodeTempleteRel.setRejectScript(rdaNodeTemplete.getRejectScript());
        return toAjax(rdaWorkflow2NodeTempleteRelService.updateRdaWorkflow2NodeTempleteRelAll(rdaWorkflow2NodeTempleteRel));
    }

    /**
     * 插入流程开始节点结束节点
     */
    public void insertStartEnd(RdaWorkflowTemplete rdaWorkflowTemplete){
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        rdaNodeTemplete.setNodeName("开始节点");
        rdaNodeTemplete.setDescription("开始节点");
        rdaNodeTemplete.setLevel(1);
        rdaNodeTemplete.setWorkflowid(rdaWorkflowTemplete.getId());
        Long userId = SecurityUtils.getUserId();
        rdaNodeTemplete.setOwnerid(userId.intValue());
        /*后期需要改成动态获取 2021-12-19***/
        rdaNodeTemplete.setTypeid(WorkflowStateid.nodeTempleteTypeid.intValue());
        rdaNodeTemplete.setPolicyid(WorkflowStateid.nodeTempletePolicyid.intValue());
        rdaNodeTemplete.setStateid(WorkflowStateid.nodeTempleteCreateid.intValue());
        rdaNodeTemplete.setNodeType(0);
        rdaNodeTempleteService.insertRdaNodeTempleteStartAndEnd(rdaNodeTemplete);

        RdaNodeTemplete rdaNodeTemplete2=new RdaNodeTemplete();
        rdaNodeTemplete2.setNodeName("结束节点");
        rdaNodeTemplete2.setDescription("结束节点");
        rdaNodeTemplete2.setLevel(2);
        rdaNodeTemplete2.setWorkflowid(rdaWorkflowTemplete.getId());
        Long userId2 = SecurityUtils.getUserId();
        rdaNodeTemplete2.setOwnerid(userId2.intValue());
        /*后期需要改成动态获取 2021-12-19***/
        rdaNodeTemplete2.setTypeid(WorkflowStateid.nodeTempleteTypeid.intValue());
        rdaNodeTemplete2.setPolicyid(WorkflowStateid.nodeTempletePolicyid.intValue());
        rdaNodeTemplete2.setStateid(WorkflowStateid.nodeTempleteCreateid.intValue());
        rdaNodeTemplete2.setNodeType(-1);
        rdaNodeTempleteService.insertRdaNodeTempleteStartAndEnd(rdaNodeTemplete2);
    }

    /**
     * 添加人员
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:assignWorkflow')")
    @PostMapping("/assignWorkflow")
    @Transactional
    public AjaxResult assignWorkflow(@RequestBody Sharing sharing){
        String idsStr=sharing.getIds();
        String[] nodeids =sharing.getToid().split(",");
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        rdaNodeTemplete.setId(Long.valueOf(nodeids[0]));
        rdaNodeTemplete.setUserId(idsStr);
        int row=rdaNodeTempleteService.updateRdaNodeTempleteAll(rdaNodeTemplete);
        return toAjax(row);
    }

    /**
     * 添加角色
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:assignRoles')")
    @PostMapping("/assignRoles")
    @Transactional
    public AjaxResult assignRoles(@RequestBody Sharing sharing){
        String idsStr=sharing.getIds();
        String[] ids =idsStr.split(",");
        String toIdsStr=sharing.getToid();
        String[] nodeids =toIdsStr.split(",");
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        rdaNodeTemplete.setId(Long.valueOf(nodeids[0]));
        rdaNodeTemplete.setRoleId(Long.valueOf(ids[0]));
        int row=rdaNodeTempleteService.updateRdaNodeTempleteAll(rdaNodeTemplete);
        return toAjax(row);
    }

    /**
     * 查询流程模板应用范围
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:workflowTemplateRangeList')")
    @GetMapping("/workflowTemplateRangeList")
    public TableDataInfo workflowTemplateRangeList(RdaWorkflowTempleteScope rdaWorkflowTempleteScope){
        startPage();
        List<RdaWorkflowTempleteScope> List=rdaWorkflowTempleteScopeService.selectRdaWorkflowTempleteScopeList(rdaWorkflowTempleteScope);
        List.forEach((RdaWorkflowTempleteScope rdaWorkflowTempleteScope2) -> {
            String typeName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope2.getObjectTypeid()));//类型
            String PolicyName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope2.getObjectPolicyid()));//策略
            String StateName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope2.getObjectStateid()));//状态
            rdaWorkflowTempleteScope2.setObjectTypeName(typeName);
            rdaWorkflowTempleteScope2.setObjectPolicyName(PolicyName);
            rdaWorkflowTempleteScope2.setObjectStateName(StateName);
        });
        return getDataTable(List);
    }



    /**
     * 添加流程模板应用范围
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:addWorkflowTemplateRange')")
    @PostMapping("/addWorkflowTemplateRange")
    public AjaxResult addWorkflowTemplateRange(@RequestBody RdaWorkflowTempleteScope rdaWorkflowTempleteScope){
        rdaWorkflowTempleteScope.setObjectCompanyid(SecurityUtils.getCompanyId());
        rdaWorkflowTempleteScope.setOwnerid(SecurityUtils.getUserId());
        rdaWorkflowTempleteScope.setWorkflowtempleteid(rdaWorkflowTempleteScope.getProjectid());

        rdaWorkflowTempleteScope.setTypeid(WorkflowStateid.workflowTempleteScopeTypeid);
        rdaWorkflowTempleteScope.setPolicyid(WorkflowStateid.workflowTempleteScopePolicyid);
        rdaWorkflowTempleteScope.setStateid(WorkflowStateid.workflowTempleteScopeCreateid);
        RdaWorkflowTempleteScope rdaWorkflowTempleteScope2=new RdaWorkflowTempleteScope();
        rdaWorkflowTempleteScope2.setName(rdaWorkflowTempleteScope.getName());
        rdaWorkflowTempleteScope2.setObjectPolicyid(rdaWorkflowTempleteScope.getObjectPolicyid());
        rdaWorkflowTempleteScope2.setObjectTypeid(rdaWorkflowTempleteScope.getObjectTypeid());
        rdaWorkflowTempleteScope2.setObjectStateid(rdaWorkflowTempleteScope.getObjectStateid());
        rdaWorkflowTempleteScope2.setObjectDeptid(rdaWorkflowTempleteScope.getObjectDeptid());
        List<RdaWorkflowTempleteScope> list=rdaWorkflowTempleteScopeService.selectRdaWorkflowTempleteScopeList(rdaWorkflowTempleteScope2);
        if(list.size()!=0){
            String typeName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope.getObjectTypeid()));//类型
            String PolicyName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope.getObjectPolicyid()));//策略
            String StateName=MapUtils.getTranscoding(redisCache,Long.valueOf(rdaWorkflowTempleteScope.getObjectStateid()));//状态
            return AjaxResult.error("抱歉当前数据已存在请勿添加重复数据,重复数据名称："+rdaWorkflowTempleteScope.getName()+"  重复数据对象类型："+typeName+"  重复数据对象策略："+PolicyName+"  重复数据对象状态："+StateName);
        }
        int row=rdaWorkflowTempleteScopeService.insertRdaWorkflowTempleteScope(rdaWorkflowTempleteScope);
        return toAjax(row);
    }

    /**
     * 删除流程模板应用范围
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:deleteWorkflowTemplateRange')")
    @DeleteMapping("/deleteWorkflowTemplateRange/{ids}")
    @Transactional
    public AjaxResult deleteScope(@PathVariable Long[] ids){
        return toAjax(rdaWorkflowTempleteScopeService.deleteRdaWorkflowTempleteScope(ids));
    }

    /**
     * 获取流程模板应用范围详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyWorkflowTemplateRange')")
    @GetMapping(value = "/modifyWorkflowTemplateRange/{id}")
    public AjaxResult modifyWorkflowTemplateRange(@PathVariable("id") Long id){
        return AjaxResult.success(rdaWorkflowTempleteScopeService.selectRdaWorkflowTempleteScopeById(id));
    }

    /**
     * 修改流程模板应用范围
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyWorkflowTemplateRange')")
    @PutMapping("/modifyWorkflowTemplateRange")
    @Transactional
    public AjaxResult modifyTemplate(@RequestBody RdaWorkflowTempleteScope rdaWorkflowTempleteScope){
        return toAjax(rdaWorkflowTempleteScopeService.updateRdaWorkflowTempleteScope(rdaWorkflowTempleteScope));
    }

    /**
     * 查询流程模板用于下拉框显示
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:workflowtemplete')")
    @GetMapping("/workflowtemplete")
    public TableDataInfo workflowtemplete(){
        List<RdaWorkflowTemplete> idName=new ArrayList<RdaWorkflowTemplete>();
        List<RdaWorkflowTemplete> rdaWorkflowTempleteList=rdaWorkflowTempleteService.selectRdaWorkflowTempleteList(new RdaWorkflowTemplete());
        rdaWorkflowTempleteList.forEach((RdaWorkflowTemplete rdaWorkflowTemplete) -> {
            RdaWorkflowTemplete rdaNodeTemplete=new RdaWorkflowTemplete();
            rdaNodeTemplete.setId(rdaWorkflowTemplete.getId());
            rdaNodeTemplete.setDescription(rdaWorkflowTemplete.getName());
            idName.add(rdaNodeTemplete);
        });
        return getDataTable(idName);
    }

    /**
     * 查询流程模板委托节点下拉显示
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeAgentList')")
    @GetMapping("/nodeAgentList")
    public TableDataInfo nodeAgentList(RdaNodeTemplete rdaNodeTemplete){
        return getDataTable(rdaNodeTempleteService.selectRdaNodeTempleteAgentList(rdaNodeTemplete.getWorkflowid(),"是"));
    }

    /**
     * 记录流程图移动坐标
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:modifyNodeList')")
    @PutMapping("/modifyNodeList")
    @Transactional
    public AjaxResult modifyNodeList(@RequestBody List<RdaNodeTemplete> rdaNodeTemplete){
        int row=0;
        Long workflowid = null;
        for(RdaNodeTemplete nodeTemplete:rdaNodeTemplete){
            RdaNodeTemplete templete=new RdaNodeTemplete();
            templete.setId(nodeTemplete.getId());
            templete.setX(nodeTemplete.getX());
            templete.setY(nodeTemplete.getY());
            workflowid=nodeTemplete.getWorkflowid();
            row=rdaNodeTempleteService.updateRdaNodeTempleteAll(templete);
        }
        RdaWorkflowTemplete rdaWorkflowTemplete=new RdaWorkflowTemplete();
        rdaWorkflowTemplete.setId(workflowid);
        rdaWorkflowTemplete.setDefaultAxis("0");
        rdaWorkflowTempleteService.updateRdaWorkflowTemplete(rdaWorkflowTemplete);
        return toAjax(row);
    }

    /**
     * 查询拒绝节点详情
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:updateRefuseNode')")
    @GetMapping("/updateRefuseNode/{id}")
    public AjaxResult updateRefuseNode(@PathVariable("id") Long id){
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel=rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelByid(id);
        if(rdaWorkflow2NodeTempleteRel.getRoadAuto()!=null){
            if(rdaWorkflow2NodeTempleteRel.getRoadAuto()){
                rdaWorkflow2NodeTempleteRel.setShowRoadAuto("1");
            }else{
                rdaWorkflow2NodeTempleteRel.setShowRoadAuto("2");
            }
        }
        return AjaxResult.success(rdaWorkflow2NodeTempleteRel);
    }

    /**
     * 修改拒绝节点
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:updateRefuseNode')")
    @PutMapping("/updateRefuseNode")
    @Transactional
    public AjaxResult updateRefuseNode(@RequestBody RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel){
        boolean check=false;
        if(rdaWorkflow2NodeTempleteRel.getRoad().equals("固定路径") &&(rdaWorkflow2NodeTempleteRel.getRoadFlag()==null || "".equals(rdaWorkflow2NodeTempleteRel.getRoadFlag()))){
            check=true;
        }else if(rdaWorkflow2NodeTempleteRel.getRoad().equals("人工路径") && (rdaWorkflow2NodeTempleteRel.getRoadFlag()!=null && rdaWorkflow2NodeTempleteRel.getRoadFlag().length()>0) && (rdaWorkflow2NodeTempleteRel.getShowRoadAuto()!=null && rdaWorkflow2NodeTempleteRel.getShowRoadAuto().length()>0)){
            if(rdaWorkflow2NodeTempleteRel.getShowRoadAuto().equals("2")){
                check=true;
            }else{
                return error("人工路径条件不满足保存失败，请填写 ’路径标识‘ 跟 ’是否自动路径‘为否再保存");
            }
        }else if(rdaWorkflow2NodeTempleteRel.getRoad().equals("自动路径") && (rdaWorkflow2NodeTempleteRel.getRoadFlag()!=null && rdaWorkflow2NodeTempleteRel.getRoadFlag().length()>0) && (rdaWorkflow2NodeTempleteRel.getShowRoadAuto()!=null && rdaWorkflow2NodeTempleteRel.getShowRoadAuto().length()>0) && (rdaWorkflow2NodeTempleteRel.getRoadAttribute()!=null && rdaWorkflow2NodeTempleteRel.getRoadAttribute().length()>0)){
            if(rdaWorkflow2NodeTempleteRel.getShowRoadAuto().equals("1")){
                check=true;
            }else{
                return error("自动路径条件不满足保存失败，请填写 ’路径标识‘ 跟 ’是否自动路径‘ 为是且 ’路径属性‘ 不为空再保存");
            }
        }else{
            if(rdaWorkflow2NodeTempleteRel.getRoad().equals("固定路径")){
                return error("固定路径条件不满足保存失败，请将 ’路径标识‘ 设置为空再保存");
            }else if(rdaWorkflow2NodeTempleteRel.getRoad().equals("人工路径")){
                return error("人工路径条件不满足保存失败，请填写 ’路径标识‘ 跟 ’是否自动路径‘为否再保存");
            }else if(rdaWorkflow2NodeTempleteRel.getRoad().equals("自动路径")){
                return error("自动路径条件不满足保存失败，请填写 ’路径标识‘ 跟 ’是否自动路径‘ 为是且 ’路径属性‘ 不为空再保存");
            }
        }

        if(check){
            if(rdaWorkflow2NodeTempleteRel.getShowRoadAuto()!=null && rdaWorkflow2NodeTempleteRel.getShowRoadAuto().length()>0){
                if(rdaWorkflow2NodeTempleteRel.getShowRoadAuto().equals("1")){
                    rdaWorkflow2NodeTempleteRel.setRoadAuto(true);
                }else if(rdaWorkflow2NodeTempleteRel.getShowRoadAuto().equals("2")){
                    rdaWorkflow2NodeTempleteRel.setRoadAuto(false);
                }
            }
            return toAjax(rdaWorkflow2NodeTempleteRelService.updateRdaWorkflow2NodeTempleteRelAll(rdaWorkflow2NodeTempleteRel));
        }
        return error("系统发生未知错误，请联系管理员");
    }


    /**
     * 查询流程模板节点拒绝列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nodeNodeTempleteRelList')")
    @GetMapping("/nodeNodeTempleteRelList")
    public TableDataInfo nodeNodeTempleteRelList(RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel){
        startPage();
        return getDataTable(rdaWorkflow2NodeTempleteRelService.selectRdaWorkflow2NodeTempleteRelAllList(rdaWorkflow2NodeTempleteRel));
    }

    /**
     * 获取流程模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:query')")
    @GetMapping(value = "/templateType/{id}")
    public TableDataInfo getTemplateTypeInfo(@PathVariable("id") Long id){
        RdaWorkflowTemplete rdaWorkflowTemplete=new RdaWorkflowTemplete();
        rdaWorkflowTemplete.setAssignmentypeid(id);
        return getDataTable(rdaWorkflowTempleteService.selectRdaWorkflowTempleteList(rdaWorkflowTemplete));
    }

    /**
     * 执行脚本校验
     */
    public static boolean checkScenario(String scenario){
        if(scenario.contains(":")){
            int count=appearNumber(scenario,":");
            if(count==1){
                String[] appovedScriptTmp1 = scenario.split(":");
                if(appovedScriptTmp1.length==1){
                    return false;
                }
                String[] moduleNames = appovedScriptTmp1[0].split("_");
                String EndstateName = appovedScriptTmp1[1];
                if (moduleNames.length >= 3) {
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 获取指定字符串出现的次数
     *
     * @param srcText 源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    /**
     * 根据类型查询策略下拉显示
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:policyTree')")
    @GetMapping("/policyTree")
    public TableDataInfo policyTree(RdaWorkflowTempleteScope rdaWorkflowTempleteScope){
        RdaPolicy rdaPolicy=new RdaPolicy();
        rdaPolicy.setTypeIds(""+rdaWorkflowTempleteScope.getObjectTypeid());
        return getDataTable(rdaPolicyService.selectRdaPolicyList(rdaPolicy));
    }

    /**
     * 根据策略查询类型下拉显示
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:stateTree')")
    @GetMapping("/stateTree")
    public TableDataInfo stateTree(RdaWorkflowTempleteScope rdaWorkflowTempleteScope){
        return getDataTable(rdaStateService.getStatesByPolicyId(rdaWorkflowTempleteScope.getObjectPolicyid()));
    }

    /**
     * 流程图保存
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:flowChartAdd')")
    @PostMapping("/flowChartAdd")
    @Transactional
    public AjaxResult flowChartAdd(@RequestBody Map<String,Object> map){
        Object rdaWorkflow2NodeTempleteRelObject = map.get("linkList");
        Object rdaNodeTempleteObject = map.get("nodeList");
        String workflowId =(String) map.get("workflowId");
        Long workflowid=Long.parseLong(workflowId);
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel=new RdaWorkflow2NodeTempleteRel();
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        List<RdaWorkflow2NodeTempleteRel> workflow2NodeTempleteRelList=(List<RdaWorkflow2NodeTempleteRel>) changeList(rdaWorkflow2NodeTempleteRelObject,rdaWorkflow2NodeTempleteRel.getClass());
        List<RdaNodeTemplete> rdaNodeTempleteList=(List<RdaNodeTemplete>) changeList(rdaNodeTempleteObject,rdaNodeTemplete.getClass());
        if(rdaNodeTempleteList!=null && rdaNodeTempleteList.size()!=0){
            //删除模板节点、模板节点关系表 重新插入
//            Long workflowid=rdaNodeTempleteList.get(0).getWorkflowid();
            rdaNodeTempleteService.deleteRdaNodeTempleteByWorkflowid(workflowid);

            rdaNodeTempleteList.forEach((RdaNodeTemplete rdaNodeTemplete2)->{
                rdaNodeTemplete2.setWorkflowid(workflowid);
                String userIds="";
                if(rdaNodeTemplete2.getUserIds()!=null){
                    for(Long userId:rdaNodeTemplete2.getUserIds()){
                        userIds+=userId+",";
                    }
                    if(userIds!=null && userIds.length()>0){
                        System.out.println(userIds.substring(0,userIds.toString().length()-1));
                        rdaNodeTemplete2.setUserId(userIds.substring(0,userIds.toString().length()-1));
                    }
                }else{
                    rdaNodeTemplete2.setUserId(null);
                }
                rdaNodeTempleteService.insertRdaNodeTempleteFlowChartAdd(rdaNodeTemplete2);
            });

            workflow2NodeTempleteRelList.forEach((RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel2)->{
                rdaWorkflow2NodeTempleteRel2.setWorkflowid(workflowid);
//                rdaWorkflow2NodeTempleteRel2.setOperationType("Approve");
                rdaWorkflow2NodeTempleteRelService.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel2);
            });
        }
        return AjaxResult.success(1);
    }

    /**
     * 查询序号
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:nextvalId')")
    @GetMapping("/nextvalId")
    public JSONObject getNextvalId(){
        Long id=rdaNodeTempleteService.selectRdaNodeTempleteNextval();
        String date="{\"id\":"+id+"}";
        JSONObject jsonobj = new JSONObject();
        JSONObject jsonObject =  JSON.parseObject(date);
        jsonobj.put("data",jsonObject);
        jsonobj.put("code",200);
        jsonobj.put("msg","操作成功");
        return jsonobj;
    }

    /**
     * Object对象转 List集合
     *
     * @param object Object对象
     * @param clazz 需要转换的集合
     * @param <T> 泛型类
     * @return
     */
    public static <T> List<T> changeList(Object object,Class<T> clazz){
        try {
            List<T> result = new ArrayList<>();
            if (object instanceof List<?>){
                for (Object o : (List<?>) object) {
                    String string = JSONObject.toJSONString(o);
                    T t = JSONObject.parseObject(string, clazz);
                    result.add(t);
                }
                return result;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下拉查询部门
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowMGMT:dept')")
    @GetMapping("/dept")
    public JSONObject dept(){
        JSONObject jsonobj = new JSONObject();
        ArrayList<String> jsonList=new ArrayList<String>();
        SysDept dept=new SysDept();
        dept.setStatus("0");
        dept.setDelFlag("0");
        List<SysDept> depts =deptService.selectDeptList(dept);
        depts.forEach((SysDept t)->{
            StringBuilder attribute=new StringBuilder();
            attribute.append("{id:"+t.getDeptId()+",name:\""+t.getDeptName()+"\"");
            attribute.append("}");
            jsonList.add(attribute.toString());
        });
        JSONArray jarr = JSONArray.fromObject(jsonList);
        jsonobj.put("rows",jarr);
        jsonobj.put("total",depts.size());
        return jsonobj;
    }
}
